//
//  ViewController.swift
//  CircularLoader
//
//  Created by 劢克科技 on 2019/3/14.
//  Copyright © 2019 劢克科技. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    let shapeLayer = CAShapeLayer()
    let shadowLayer = CAShapeLayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        let shadowPath = UIBezierPath(arcCenter: CGPoint.zero, radius: 100, startAngle: 0, endAngle: CGFloat.pi * 2, clockwise: true)
        shadowLayer.path = shadowPath.cgPath
        shadowLayer.fillColor = UIColor.yellow.cgColor
        shadowLayer.position = view.center
        view.layer.addSublayer(shadowLayer)
        shadowScaleAnimation()
        
        let circlePath = UIBezierPath(arcCenter: view.center, radius: 100, startAngle: -CGFloat.pi / 2, endAngle: CGFloat.pi * 2, clockwise: true)
        
        let trackLayer = CAShapeLayer()
        trackLayer.path = circlePath.cgPath
        trackLayer.fillColor = UIColor.clear.cgColor
        trackLayer.strokeColor = UIColor.lightGray.cgColor
        trackLayer.lineCap = .round
        trackLayer.lineWidth = 10
        
        view.layer.addSublayer(trackLayer)
        
        shapeLayer.path = circlePath.cgPath
        shapeLayer.fillColor = UIColor.white.cgColor
        shapeLayer.strokeColor = UIColor.red.cgColor
        shapeLayer.lineCap = .round
        shapeLayer.lineWidth = 10
        shapeLayer.strokeEnd = 0
        
        view.layer.addSublayer(shapeLayer)
    }
    
    fileprivate func beginDownloadFile() {
        print("begin download file...")
    }

    fileprivate func animateStart() {
        let animation = CABasicAnimation(keyPath: "strokeEnd")
        animation.duration = 2
        animation.toValue = 1
        animation.fillMode = .forwards
        animation.isRemovedOnCompletion = false
        
        shapeLayer.add(animation, forKey: "urSoBasic")
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        beginDownloadFile()
        
        animateStart()
    }

    fileprivate func shadowScaleAnimation() {
        let animation = CABasicAnimation(keyPath: "transform.scale")
        
        animation.toValue = 1.5
        animation.duration = 0.8
        animation.autoreverses = true
        animation.repeatCount = Float.infinity
        shadowLayer.add(animation, forKey: "shadow")
    }
}

